package com.qiguliuxing.dts.service.notify;

import com.google.common.collect.Maps;
import com.qiguliuxing.dts.core.notify.NotifyType;
import com.qiguliuxing.dts.db.bean.DtsUserSeckillSubInfo;
import com.qiguliuxing.dts.db.bean.SeckillGoodsVo;
import com.qiguliuxing.dts.db.domain.DtsSeckillBatch;
import com.qiguliuxing.dts.service.base.DtsGoodsSeckillService;
import com.qiguliuxing.dts.service.base.DtsUserSeckillSubService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liumeng
 */
@Service
public class SecondSeckillNotifyService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private DtsUserSeckillSubService dtsUserSeckillSubService;

    @Autowired
    private DtsGoodsSeckillService dtsGoodsSeckillService;

    /**
     * 秒杀开始前几分钟进行通知
     */
    private final static int SKILL_NOTIFY_MAX_DIFF = 5;
    private final static int SKILL_NOTIFY_MIN_DIFF = 0;

    public void notifyUserSeckill(DtsSeckillBatch timeBean, List<DtsUserSeckillSubInfo> noticeUserList){
        //开始前5分钟进行通知
        long minDiff = calcDifferMinute(timeBean.getTime());
        if(minDiff <= SKILL_NOTIFY_MAX_DIFF && minDiff >= SKILL_NOTIFY_MIN_DIFF){
            //查询今日秒杀物品
            List<SeckillGoodsVo> goods = this.getDtsSeckillGoods(Integer.valueOf(timeBean.getId()));
            Map<Integer, SeckillGoodsVo> seckillGoodsMap = Optional.ofNullable(goods).orElse(new ArrayList<>()).stream().collect(Collectors.toMap(SeckillGoodsVo::getId, e -> e));
            noticeUserList.forEach(userInfo ->{
                SeckillGoodsVo goodsInfo = seckillGoodsMap.get(userInfo.getGoodsId());
                if(goodsInfo != null){
                    String title = goodsInfo.getGoodsName();
                    String[] params = new String[]{title.substring(0,15)+"...",timeBean.getTime(),goodsInfo.getSeckillPrice()+"元"};
                    notifyService.subWxTemplate(userInfo.getWeixinOpenid(), NotifyType.SKILL_SUBSCRIBE,params,"/pages/seckillDetail/seckillDetail?id="+userInfo.getGoodsId());
                    this.updateNoticed(userInfo.getId());
                }
            });
        }
    }

    private void updateNoticed(Integer id){
        dtsUserSeckillSubService.updateNoticed(id);
    }

    public List<SeckillGoodsVo> getDtsSeckillGoods(Integer batchId){
        Map<String, Object> param = Maps.newHashMap();
        param.put("offset", 0);
        param.put("limit", 1000);
        param.put("batchId", batchId);
        param.put("status", 1);
        return dtsGoodsSeckillService.querySeckillGoods(param);
    }

    public static long calcDifferMinute(String hour) {
        Date cd = Calendar.getInstance().getTime();
        String d = DateFormatUtils.format(cd,"yyyy-MM-dd");
        String time = d+ " "+hour;
        Date start = null;
        try {
            start = DateUtils.parseDate(time,"yyyy-MM-dd HH:mm");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return getDatePoor(start,cd);
    }

    public static long getDatePoor(Date endDate, Date nowDate) {
        long nm = 1000 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少分钟
        long min = diff / nm;
        return min;
    }
}
